"""
file_name：read_com.py
author：王鑫
date：2019-04-19
file_description：读取 Powercast P2110 开发板串口数据
"""
import threading
import time
import serial
import p2110


class ComThread:
    def __init__(self, port='COM3', baudrate=19200, c_time=2):
        """
        初始化串口数据
        :param port: 串口端口号
        :param baudrate: 串口波特率
        :param c_time: 串口等待时间
        """
        # 串口对象
        self.serial = None
        # 串口助手工作状态
        self.alive = False
        self.waitEnd = None
        # 串口端口号
        self.port = port
        # 串口波特率
        self.baudrate = baudrate
        # 等待时间
        self.time = c_time
        self.ID = None
        self.data = None

    # 串口等待函数
    def waiting(self):
        if self.waitEnd is not None:
            self.waitEnd.wait()

    # 串口关闭
    def set_stop_event(self):
        if self.waitEnd is not None:
            self.waitEnd.set()
        self.alive = False
        self.stop()

    # 串口启动
    def start(self):
        self.serial = serial.Serial('COM3', 19200)
        self.serial.port = self.port
        self.serial.baudrate = self.baudrate
        self.serial.timeout = self.time
        if self.serial.isOpen() is False:
            self.serial.open()

        # 判断串口是否已经打开
        if self.serial.isOpen():
            self.waitEnd = threading.Event()
            self.alive = True
            return True
        else:
            return False

    # 发送数据
    def send_date(self, data):
        if isinstance(data):
            data = data.encode('utf-8')
        try:
            self.serial.write(data)
        except Exception as ex:
            print(str(ex))

    # 读取数据
    def read(self):
        while self.alive:
            data = ''
            data = data.encode('utf-8')
            is_waiting = self.serial.inWaiting()

            if is_waiting:
                while len(data) < 150:
                    data = data + self.serial.read(is_waiting)
                print('%s: %s' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), data))
                # 下面将数据封装到p2110类对象中
                p = p2110.P2110()
                # 将数据保存到文件中
                # p.get_info(data=data)
                # p.write_to_file("data.csv")

    # 停止读取数据
    def stop(self):
        self.alive = False
        if self.serial.isOpen():
            self.serial.close()


def main():
    """
    调用串口来读取数据
    :return:
    """
    com1 = ComThread()
    try:
        if com1.start():
            print('串口名称：%s  波特率：%s' % (com1.serial.name, com1.serial.baudrate))
            print('*'*200)
            com1.read()
            com1.waiting()
            com1.stop()
        else:
            print('启动失败')

    except Exception as ex:
        print('异常：'+str(ex))
    # 关闭系统
    if com1.alive:
        com1.stop()


if __name__ == '__main__':
    main()
